package com.wnhz.work.yz.activity;

import android.animation.Animator;
import android.animation.ValueAnimator;
import android.content.Intent;
import android.graphics.Path;
import android.graphics.PathMeasure;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.animation.LinearInterpolator;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.wnhz.work.yz.BaseActivity;
import com.wnhz.work.yz.R;
import com.wnhz.work.yz.base.BaseRVAdapter;
import com.wnhz.work.yz.base.BaseViewHolder;
import com.wnhz.work.yz.bean.Finish1;
import com.wnhz.work.yz.bean.Install2Bean;
import com.wnhz.work.yz.listener.addListener;
import com.wnhz.work.yz.utils.Url;
import com.wnhz.work.yz.utils.xutils3.MyCallBack;
import com.wnhz.work.yz.utils.xutils3.XUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.x;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class InstallDetails1Activity extends BaseActivity implements View.OnClickListener, addListener {
    private RecyclerView recycler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_install_details);
        EventBus.getDefault().register(this);
      //  MyApplication.getInstance().addDestoryActivity(this, "install1");
        initTitle();
        upLoad("");
        initView();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(Finish1 event) {
        finish();
    }


    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);//反注册EventBus
        super.onDestroy();
    }
    private ImageView cart_img;
    private TextView price, nums;
    private EditText edit;
    private LinearLayout ll_search;
    private RelativeLayout rl;

    private void initView() {
        rl = (RelativeLayout) findViewById(R.id.rl);
        cart_img = (ImageView) findViewById(R.id.cart_img);
        ll_search = (LinearLayout) findViewById(R.id.ll_search3);
        nums = (TextView) findViewById(R.id.nums);
        price = (TextView) findViewById(R.id.price);
        findViewById(R.id.quxiao).setOnClickListener(this);
        findViewById(R.id.look).setOnClickListener(this);
        findViewById(R.id.gopay).setOnClickListener(this);

        recycler = (RecyclerView) findViewById(R.id.recycler);
        recycler.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        edit = (EditText) findViewById(R.id.search);
        edit.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEND || (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                    upLoad(edit.getText().toString());
                    return true;
                }
                return false;
            }
        });
    }


    private String pid = "";
    private String name = "";

    private void initTitle() {
        pid = getIntent().getStringExtra("pid");
        name = getIntent().getStringExtra("name");
        TextView title = (TextView) findViewById(R.id.view_main_middle_title);
        title.setText("" + name);
        findViewById(R.id.btn_main_left).setOnClickListener(this);
        ImageView ic_telephone = (ImageView) findViewById(R.id.ic_telephone);
        ic_telephone.setImageResource(R.mipmap.ic_search);
        ic_telephone.setOnClickListener(this);
        ic_telephone.setVisibility(View.GONE);
    }

    private List<Install2Bean.InfoEntity.ListEntity> list = new ArrayList<>();

    private void upLoad(String str) {
        Map<String, Object> map = new HashMap<>();
        map.put("pid", pid);
        map.put("type", "0");
        map.put("keywords", str);
        showDialog();
        XUtil.Post(Url.DECORATE_DETAIL, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Log.i("----", "onSuccess:= " + result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String res = jsonObject.optString("result");
                    if ("1".equals(res)) {
                        Gson gson = new Gson();
                        Install2Bean bean = gson.fromJson(result, Install2Bean.class);
                        Install2Bean.InfoEntity info = bean.getInfo();
                        list = info.getList();
                        setData();
                        recycler.setVisibility(View.VISIBLE);
                    } else {
                        String info = jsonObject.optString("info");
                        if ("-1".equals(res)) {
                            info = "请重新登录";
                        }
                        MyToast(info);
                        recycler.setVisibility(View.GONE);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                closeDialog();
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                closeDialog();
                ex.printStackTrace();
            }
        });

    }

    private ArrayList<Install2Bean.InfoEntity.ListEntity> list2 = new ArrayList<>();

    private BaseRVAdapter adapter;

    private void setData() {
        adapter = new BaseRVAdapter(this, list) {
            @Override
            public int getLayoutId(int viewType) {
                return R.layout.item_install_detail1_11;
            }

            @Override
            public void onBind(final BaseViewHolder holder, final int position) {
                x.image().bind(holder.getImageView(R.id.img), list.get(position).getGoods_img());
                holder.setTextView(R.id.text_title, list.get(position).getGoods_name());
                holder.setTextView(R.id.text_desc, list.get(position).getGoods_des());
                holder.setTextView(R.id.text_price, list.get(position).getPrice());
                holder.getView(R.id.ll_max).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        int k = -1;
                        for (int j = 0; j < list2.size(); j++) {
                            if (list.get(position).getGoods_id().equals(list2.get(j).getGoods_id())) {
                                k = j;
                            }
                        }
                        addCart(position, holder.getImageView(R.id.img));
                        if (k == -1) {
                            list.get(position).setNum("1");
                            list2.add(list.get(position));
                            String num2 = "共计：<color=\"#ff0000\">" + list2.size() + "</color>个服务项目";
                            nums.setText(Html.fromHtml(num2));
                        } else {
                            Log.e("---", list2.get(k).getNum() + "---");
                            list2.get(k).setNum("" + (Integer.parseInt(list2.get(k).getNum()) + 1) + "");
                        }
                        Double total = 0d;
                        for (int n = 0; n < list2.size(); n++) {
                            total += Double.parseDouble(list2.get(n).getPrice()) * Double.parseDouble(list2.get(n).getNum());
                        }
                        DecimalFormat df = new DecimalFormat("######0.00");
                        price.setText("￥" + df.format(total));
                    }
                });

            }
        };
        recycler.setAdapter(adapter);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_main_left:
                finish();
                break;
            case R.id.ic_telephone:
                ll_search.setVisibility(View.VISIBLE);
                break;
            case R.id.quxiao:
                upLoad("");
                ll_search.setVisibility(View.VISIBLE);
                break;
            case R.id.look:
                if (list2.size() == 0) {
                    MyToast("请至少选择一个");
                    return;
                }
                startActivityForResult(new Intent(this, LookDetails1Activity.class).putExtra("list", list2).putExtra("pid", pid).putExtra("type", "0"), 8888);
                break;
//            case R.id.gopay:
//                if (list == null) {
//                    return;
//                }
//                int k1=0;
//                ArrayList<Install2Bean.InfoEntity.ListEntity> list3 = new ArrayList<>();
//                for (int i = 0; i < list.size(); i++) {
//                    if (Integer.parseInt(list.get(i).getNum()) > 0) {
//                        list3.add(list.get(i));
//                    }else{
//                        k1++;
//                    }
//                }
//                if (k1==list.size()){
//                    MyToast("请至少选择一个");
//                    return;
//                }
//                startActivity(new Intent(this, Details1ToPayActivity.class).putExtra("list", list3));
//                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 8888 && resultCode == RESULT_OK) {
            list2 = (ArrayList<Install2Bean.InfoEntity.ListEntity>) data.getSerializableExtra("list");
            String num2 = "共计：<color=\"#ff0000\">" + list2.size() + "</color>个服务项目";
            nums.setText(Html.fromHtml(num2));
            Double total = 0d;
            for (int n = 0; n < list2.size(); n++) {
                total += Double.parseDouble(list2.get(n).getPrice()) * Double.parseDouble(list2.get(n).getNum());
            }
            DecimalFormat df = new DecimalFormat("######0.00");
            price.setText("￥" + df.format(total));

        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private float[] mCurrentPosition = new float[2];
    private PathMeasure mPathMeasure;

    @Override
    public void addCart(int position, ImageView imgview) {

        int parent[] = new int[2];
        rl.getLocationInWindow(parent);
        Log.e("tag", parent[0] + "@" + parent[1]);

        int startLoc[] = new int[2];
        imgview.getLocationInWindow(startLoc);
        int endLoc[] = new int[2];
        cart_img.getLocationInWindow(endLoc);


        final ImageView goods = new ImageView(getApplicationContext());
        goods.setImageDrawable(imgview.getDrawable());
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(100, 100);

        rl.addView(goods, params);

        float startX = startLoc[0];
        float startY = startLoc[1] - parent[1];
        float toX = endLoc[0] + cart_img.getWidth() / 3;
        float toY = endLoc[1];


        Path path = new Path();
        path.moveTo(startX, startY);
        path.quadTo((startX + toX) / 2, startY, toX, toY);
        mPathMeasure = new PathMeasure(path, false);


        //属性动画实现
        ValueAnimator valueAnimator = ValueAnimator.ofFloat(0, mPathMeasure.getLength());
        valueAnimator.setDuration(1000);
        // 匀速插值器
        valueAnimator.setInterpolator(new LinearInterpolator());
        valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float value = (Float) animation.getAnimatedValue();
                // 获取当前点坐标封装到mCurrentPosition
                mPathMeasure.getPosTan(value, mCurrentPosition, null);
                goods.setTranslationX(mCurrentPosition[0]);
                goods.setTranslationY(mCurrentPosition[1]);
            }
        });
        valueAnimator.start();


        valueAnimator.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {

            }

            @Override
            public void onAnimationEnd(Animator animation) {
                rl.removeView(goods);
            }

            @Override
            public void onAnimationCancel(Animator animation) {

            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }
        });


    }
}
